package net.binarism.journal
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.IDataInput;
	import flash.utils.IDataOutput;
	import flash.utils.IExternalizable;
	
	import mx.controls.Alert;
		
	public class PreferencesManager implements IExternalizable
	{
		public static const JOURNAL_LOCATION:String = "journal_location"; 
		
		private var _prefValues:Dictionary;
		private   var   _prefsStream:FileStream;
		
		
		public function PreferencesManager(){
			_prefValues = new Dictionary();
			loadPreferences();
		}
		
		
		public function setPreference( name:String, value:Object ):void {
			_prefValues[ name ] = value;
			savePreferences();
		}
		
		
		public function getPreference( name:String ):Object {
			return _prefValues[ name ];
		}
		
			
		public function loadPreferences():void {
			var fp: File = File.applicationStorageDirectory;
			
			fp = fp.resolvePath( "prefs.xml" );
			
			if ( fp.exists ) {
				
				_prefsStream = new FileStream();
				_prefsStream.open( fp, FileMode.READ);
				
				readExternal( _prefsStream );
				_prefsStream.close();
			} else {
				_prefValues[ "appName" ] = "tracker"; // test-code
				savePreferences();
			}
		}
		
		
		public function savePreferences():void {
			var fp: File = File.applicationStorageDirectory;
			
			fp = fp.resolvePath( "prefs.xml" );
			
			_prefsStream = new FileStream();
			_prefsStream.open( fp, FileMode.WRITE );
			
			writeExternal( _prefsStream );
			_prefsStream.close();
		}
		
		
		public function readExternal(input:IDataInput):void
		{
			var bytes:ByteArray = new ByteArray();
			input.readBytes( bytes, 0, input.bytesAvailable );
			
			var q:Object = bytes.readObject();
				
			_prefValues = new Dictionary();
				
			for( var p:Object in q ) {
				_prefValues[ p ] = q[p];
			}
		}
		
			
		public function writeExternal(output:IDataOutput):void
		{
			var bytes:ByteArray = new ByteArray();
			bytes.writeObject( _prefValues );
			
			output.writeBytes( bytes );
		}
	}
}